import { useEffect, useRef, useState } from "react";
import styles from "./index.module.less";
import { ProForm, ProFormInstance, ProFormSelect, ProFormText } from "@ant-design/pro-components";
import { Affix, Button, Col, ConfigProvider, Flex, Row, Space, message, Typography, Breadcrumb } from "antd";
import { useNavigate } from "react-router-dom";
import { CheckCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { MAIN_PRIMARY_COLOR } from "@/enums";
import { omit, map, isEmpty, join } from "lodash";
import useUrl from "@/hooks/useUrl";
import { useRequest } from "ahooks";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import dayjs from "dayjs";
import { emojiRegex, newlineRegex } from "@/pages/product/Create";
import { getCategoryList, getCourseDetail, getModalityList, saveCourseApi } from "@/api/modules/course";
import Upload from "@/components/Upload";
import { Video } from "@icon-park/react";
import { getQiniuyunToken } from "@/api/modules/user";

const { Text } = Typography;

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const course_id = query.get("id");
	const isView = query.get("isView") == 1;
	const [isEdit, setIsEdit] = useState<any>(!isView);
	const { loading, runAsync } = useRequest(saveCourseApi, { manual: true });
	const { loading: loadingDetail, runAsync: getDetailRunAsync, data } = useRequest(getCourseDetail, { manual: true });
	const [uploadAuthInfo, setUploadAuthInfo] = useState<any>({});

	const DETAIL_DATA = data?.data || {};

	useEffect(() => {
		// getQiniuyunToken().then((res: any) => {
		// 	console.log("========res:", res);
		// 	setUploadAuthInfo({
		// 		token: res?.data,
		// 		useCdnDomain: true
		// 	});
		// });
	}, []);

	useEffect(() => {
		if (course_id)
			getDetailRunAsync({ course_id }).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					const data = res?.data ?? {};

					const InitialData = {
						...data
					};

					formRef.current?.setFieldsValue(InitialData);
				}
			});
	}, []);

	useEffect(() => {
		if (!course_id) formRef.current?.resetFields();
	}, [course_id]);

	const handleValuesChange = (changeValue: any) => {
		if (Object.hasOwn(changeValue, "course_name") && typeof changeValue.course_name === "string") {
			const newName = changeValue.course_name.replace(emojiRegex, "").replace(newlineRegex, "");
			formRef.current?.setFieldValue("course_name", newName);
		}
	};

	const handleSubmit = (type: "add" | "edit" | "draft") => {
		const values = formRef.current?.getFieldsFormatValue?.();
		const requestData = {
			...values,
			course_id
		};
		if (!values.tx_vid && !values.video) {
			message.error("腾讯视频VID和课程视频必填一个！");
			return;
		}
		const callback = () => {
			runAsync(requestData, type).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success(course_id ? "保存成功" : "创建成功");
					handleBack();
				}
			});
		};
		if (type === "draft") {
			callback();
			return;
		}
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleBack = () => {
		if (isView) {
			setIsEdit(false);
			return;
		}
		navigate("/courses");
	};

	const items = [
		{
			title: "全部课程",
			href: "/courses"
		},
		{
			title: "查看课程",
			className: styles.active
		}
	];

	return (
		<ConfigProvider
			theme={{
				components: {
					Radio: {
						wrapperMarginInlineEnd: 60
					},
					Checkbox: {
						marginXS: 60,
						borderRadiusSM: 50
					}
				}
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.container}>
					<ProForm
						disabled={!isEdit}
						colon={false}
						submitter={false}
						formRef={formRef}
						layout="horizontal"
						onValuesChange={handleValuesChange}
						labelCol={{ span: 4 }}
					>
						<div className={styles.content_wrap}>
							<div className={styles.content}>
								{Boolean(course_id) && (
									<Row>
										<Col span={4}></Col>
										<Col span={20}>
											<Breadcrumb className={styles.breadcrumb} separator=">" items={items} />
										</Col>
									</Row>
								)}

								<Row style={{ height: "32px", marginBottom: "12px" }}>
									<Col span={4}>
										<div className={styles.title}>课程信息</div>
									</Col>
								</Row>
								{Boolean(course_id) && (
									<Row style={{ marginBottom: "12px", height: "32px" }}>
										<Col span={4}>
											<label className={styles.label}>课程ID</label>
										</Col>
										<Col span={20}>
											<Text copyable={{ icon: <a>复制</a> }}>{DETAIL_DATA?.course_id}</Text>
										</Col>
									</Row>
								)}
								<ProFormText
									label="课程名称"
									name="course_name"
									rules={[{ required: true, message: "请输入" }]}
									placeholder={"最多允许输入20个汉字"}
									extra={<div>标题中请勿使用表情符号、换行符号。</div>}
									fieldProps={{
										showCount: true,
										maxLength: 20
									}}
								/>
								<ProFormSelect
									label="课程形式"
									name={"base_course_category_id"}
									placeholder={"请选择课程形式"}
									rules={[{ required: true, message: "请选择" }]}
									request={async () => {
										const res = await getModalityList();

										return map(res?.data, item => ({
											label: item?.base_course_category_name,
											value: item?.base_course_category_id
										}));
									}}
									fieldProps={{
										style: { width: "320px" }
									}}
								/>
								<ProFormSelect
									label="课程类别"
									name={"course_menus_id"}
									placeholder={"请选择课程类别"}
									rules={[{ required: true, message: "请选择" }]}
									request={async () => {
										const res = await getCategoryList();

										return map(res?.data, item => ({
											label: item?.course_menus_name,
											value: item?.course_menus_id
										}));
									}}
									fieldProps={{
										style: { width: "320px" }
									}}
								/>
								<ProFormText
									label="授课人"
									name="teacher"
									rules={[{ required: true, message: "请输入" }]}
									placeholder={"请输入授课人姓名"}
								/>
								<ProFormText
									label="授课人头衔"
									name="teacher_label"
									rules={[{ required: true, message: "请输入" }]}
									placeholder={"请输入授课人头衔，比如：教授"}
									fieldProps={{
										showCount: true,
										maxLength: 10
									}}
								/>
								<ProFormText
									label="授课人介绍"
									name="teacher_desc"
									rules={[{ required: true, message: "请输入" }]}
									placeholder={"请输入授课人介绍"}
								/>
								<ProForm.Item label="授课人头像" name="teacher_avatar" rules={[{ required: true, message: "请上传" }]}>
									<Upload
										canRemove={!isView}
										isView={isView}
										resFormat={res => join(map(res, "url"), ",")}
										maxSize={3}
										msg={"图片要求：比例为1:1，大小3m内；"}
									/>
								</ProForm.Item>
								<ProFormText
									label="课程简介"
									name="description"
									rules={[
										{ required: true, message: "请输入" },
										{ max: 300, message: "字数限制300个以内" }
									]}
									placeholder={"最多允许输入300个字符"}
								/>
								<ProFormText
									label="腾讯视频VID"
									name="tx_vid"
									rules={[{ max: 100, message: "字数限制100个以内" }]}
									placeholder={"请输入腾讯视频VID"}
								/>
								<div className={styles.up_wrap}>
									<div className={styles.detail_img}>
										<ProForm.Item label="课程详情图" name="description_img">
											<Upload
												canRemove={!isView}
												isView={isView}
												resFormat={res => join(map(res, "url"), ",")}
												maxSize={15}
												msg={"非必填，图片要求：宽度750px，高度不限，小于15M的JPG/PNG格式图片；"}
											/>
										</ProForm.Item>
									</div>
									<ProForm.Item label="课程封面图" name="course_cover_img" rules={[{ required: true, message: "请上传" }]}>
										<Upload
											canRemove={!isView}
											isView={isView}
											resFormat={res => join(map(res, "url"), ",")}
											maxSize={15}
											msg={"图片要求：比例为4:3，大小3m内；"}
										/>
									</ProForm.Item>
									<div className={styles.video_wrap}>
										<ProForm.Item label="课程视频" name="video">
											<Upload
												canRemove={!isView}
												isView={isView}
												resFormat={res => join(map(res, "url"), ",")}
												maxSize={200}
												msg={"视频要求：比例为4:3，大小200m内；"}
												accept={".avi,.mp4,.mov,video/mp4,video/x-m4v,video/*"}
												uploadNode={
													<Flex vertical={true} align="center" justify="center">
														<PlusOutlined style={{ fontSize: "18px", color: "#8F8F8F" }} />
														<span style={{ color: "#8F8F8F" }}>上传视频</span>
													</Flex>
												}
												iconRender={() => <Video theme="outline" size="24" fill="#333" />}
												// url={"https://upload.qiniup.com"}
												// data={uploadAuthInfo}
											/>
										</ProForm.Item>
									</div>
								</div>
							</div>
						</div>
					</ProForm>
					{isEdit ? (
						<Affix offsetBottom={0}>
							<Flex justify="center" className={styles.btns}>
								<Space size={10}>
									<Button ghost type="primary" onClick={() => handleBack()}>
										{course_id ? "取消" : "取消课程"}
									</Button>
									{/* <Button loading={loading} ghost type="primary" onClick={() => handleSubmit("draft")}>
											保存草稿
										</Button> */}
									<Button loading={loading} type="primary" onClick={() => handleSubmit(course_id ? "edit" : "add")}>
										{course_id ? "保存" : "创建课程"}
									</Button>
									{course_id && DETAIL_DATA?.updated_at && (
										<Space size={10}>
											<CheckCircleOutlined style={{ color: MAIN_PRIMARY_COLOR }} />
											<span style={{ color: "#000" }}>
												最后保存于{dayjs(DETAIL_DATA?.updated_at).format("YYYY-MM-DD HH:mm:ss")}
											</span>
										</Space>
									)}
								</Space>
							</Flex>
						</Affix>
					) : (
						<Affix offsetBottom={0}>
							<Flex justify="center" className={styles.btns}>
								<Space size={10}>
									<Button ghost type="primary" onClick={() => navigate(-1)}>
										返回
									</Button>
									<Button type="primary" onClick={() => setIsEdit(true)}>
										编辑
									</Button>
								</Space>
							</Flex>
						</Affix>
					)}
				</div>
			</Loading>
		</ConfigProvider>
	);
};
